package com.example.layui.config;

import com.example.layui.mapper.MenuMapper;
import com.example.layui.pojo.Menu;
import com.example.layui.pojo.Role;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    AntPathMatcher antPathMatcher=new AntPathMatcher();
    @Resource
    MenuMapper menuMapper;
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String url=((FilterInvocation)object).getRequestUrl();
        if ("/login".equals(url)) {
            return null;
        }
        List<Menu> menus=menuMapper.getAllMenu();
        for (Menu menu :menus){
            if(antPathMatcher.match(menu.getUrl(),url)){
                List<Role> roles=menu.getRoles();
                String [] roleArray=new String[roles.size()];
                for (int i=0;i<roleArray.length;i++){
                    roleArray[i]=roles.get(i).getName();
                }
                return SecurityConfig.createList(roleArray);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
